import qs from 'qs';
import GlobalConstant from '@/config/global-constant';
import { Interceptors } from './interceptors';
export class HttpService {
    public axios: any;
    constructor() {
        // 获取axios实例
        this.axios = new Interceptors().getInterceptors();
    }
    /**
     * get请求
     * @param url 请求链接
     * @param params 请求参数
     */
    public get(url: string, params?: object, config?: any):Promise<any> {    
        if(params) {
            url = `${url}?${qs.stringify(params)}`
        };
        return new Promise((resolve, reject) => {
            this.axios.get(url, config).then((res: any) => {
                this.resultHandle(res, resolve, reject);
            }).catch((err: { message: any; }) => {
                reject(err.message);
            });
        });

    }

    /**
     * post请求
     * @param url 
     * @param params 
     */
    public post(url: string, params?: object, config?: any):Promise<any> {
        return new Promise((resolve, reject) => {
            this.axios.post(url, params, config).then((res: any) => {
                this.resultHandle(res, resolve, reject);
            }).catch((err: { message: any; }) => {
                reject(err.message);
            });
        });

    }

    /**
     * @param res
     * @param resolve
     */
    public resultHandle(res: any, resolve: { (value: any): void; (value: any): void; (arg0: any): void; }, reject: { (reason?: any): void; (reason?: any): void; }) {
        if (res.code === '0') {
            resolve(res);
        } else {
            this.errorHandle(res, resolve, reject);
        }
    }

    /**
     * 服务端状态处理,例如中断性异常,退出异常等等(与拦截器http握手状态注意区分)
     * @param res
     */
    public errorHandle(res: any, resolve: (arg0: any) => void, reject: (arg0: any) => void) {
        // message.warn(res.msg);  // 统一谈服务端提示,我们提示统一由服务端提供
        // 状态码判断 不同状态码操作不同
        switch (res.code) {
            case 'S00A0002': 
                sessionStorage.removeItem(GlobalConstant.TOKEN);
                if(res.msg) {
                    res.message = res.msg
                }
                reject(res)
                break;
            default:
                resolve(res)
        }
    }

    // @debounce(1000)
    // public noLogin() {
    //     modalService.warn({
    //         title: '系统提示',
    //         content: '登入超时，请重新登入！',
    //         onOk: () => {
    //             router.push({
    //                 path: '/login-register/login'
    //             })
    //         },
    //         onCancel: () => {
    //             router.push({
    //                 path: '/index'
    //             })
    //         }
    //     });
    // }

}


export default new HttpService()
